package maps

import "github.com/mitchellh/mapstructure"

type structure struct {
	Conf *mapstructure.DecoderConfig
}

func NewStructure() *structure {
	return &structure{}
}

// 重置信息
func (ms *structure) ResetConf(conf *mapstructure.DecoderConfig) *structure {
	ms.Conf = conf
	return ms
}

// 设置是否支持弱类型转化
func (ms *structure) ConfWeak(weakly bool) *structure {
	if ms.Conf == nil {
		ms.Conf = &mapstructure.DecoderConfig{}
	}
	ms.Conf.WeaklyTypedInput = weakly
	return ms
}

// 设置信息存储
func (ms *structure) ConfMetadata(metadata *mapstructure.Metadata) *structure {
	if ms.Conf == nil {
		ms.Conf = &mapstructure.DecoderConfig{}
	}
	ms.Conf.Metadata = metadata
	return ms
}

// map 转换成 struct
func (ms *structure) ToStruct(m map[string]interface{}, s any) error {
	if ms.Conf != nil {
		ms.Conf.Result = &s
		decoder, err := mapstructure.NewDecoder(ms.Conf)
		if err != nil {
			return err
		}
		return decoder.Decode(m)
	}
	return mapstructure.Decode(m, s)
}

// struct 转换成 map
func (ms *structure) ToMap(s any, m *map[string]interface{}) error {
	return mapstructure.Decode(s, m)
}
